package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.WorkOrderErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.workorder.pojo.dto.WorkOrderEvaluateDTO;
import com.xbongbong.pro.workorder.pojo.dto.WorkOrderEvaluateSaveDTO;
import com.xbongbong.pro.workorder.pojo.vo.WorkOrderEvaluateSaveVO;
import com.xbongbong.pro.workorder.pojo.vo.WorkOrderEvaluateVO;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.WorkOrderEvaluateEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateEntity;
import com.xbongbong.saas.domain.entity.ext.WorkOrderEvaluateEntityExt;
import com.xbongbong.saas.enums.WorkOrderStatusEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.model.WorkOrderEvaluateModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WorkOrderTemplateModel;
import com.xbongbong.saas.service.WorkOrderEvaluationService;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author 刘阳
 * @date 2019/4/15 3:22 PM
 * @since v1.0
 * @version v1.0
 */
@Service("workOrderEvaluationService")
public class WorkOrderEvaluationServiceImpl implements WorkOrderEvaluationService {

    private static final Logger LOG = LoggerFactory.getLogger(WorkOrderEvaluationServiceImpl.class);

    @Resource
    private WorkOrderEvaluateModel workOrderEvaluateModel;

    @Resource
    private UserModel userModel;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private WorkOrderTemplateModel workOrderTemplateModel;

    /**
     * Description: 查看评价
     * @param workOrderEvaluateDTO
     * @return WorkOrderEvaluateVO
     * @throws XbbException
     * @author 刘阳
     * @date 2019/4/15 2:22 PM
     * @since v1.0
     */
    @Override
    public WorkOrderEvaluateVO getEvaluation(WorkOrderEvaluateDTO workOrderEvaluateDTO) throws XbbException {
        WorkOrderEvaluateVO workOrderEvaluateVO = new WorkOrderEvaluateVO();
        try {
            String corpid = workOrderEvaluateDTO.getCorpid();
            Long workOrderId = workOrderEvaluateDTO.getId();
            WorkOrderEvaluateEntity workOrderEvaluateEntity = workOrderEvaluateModel.getByWorkOrderId(workOrderId, corpid);
            WorkOrderEvaluateEntityExt workOrderEvaluateEntityExt = new WorkOrderEvaluateEntityExt();
            if (workOrderEvaluateEntity != null) {
                BeanUtil.copyProperties(workOrderEvaluateEntity, workOrderEvaluateEntityExt);
                String userId = workOrderEvaluateEntity.getEvaluateId();
                UserEntity userEntity = userModel.getByKey(userId, corpid);
                if (userEntity == null) {
                    // 外部评价人 或 已离职
                    workOrderEvaluateEntityExt.setEvaluator("");
                } else {
                    workOrderEvaluateEntityExt.setEvaluator(userEntity.getName());
                }
                workOrderEvaluateVO.setWorkOrderEvaluateEntity(workOrderEvaluateEntityExt);
            }
            workOrderEvaluateVO.setWorkOrderEvaluateEntity(workOrderEvaluateEntityExt);

            WorkOrderEntity workOrderEntity = workOrderModel.getByKey(workOrderId, corpid);
            if (Objects.equals(workOrderEntity.getStatus(), WorkOrderStatusEnum.FINISH.getCode())) {
                workOrderEvaluateVO.setIsFinish(1);
            } else {
                workOrderEvaluateVO.setIsFinish(0);
            }

            //判断是否可以评价
            WorkOrderTemplateEntity workOrderTemplateEntity = workOrderTemplateModel.getBykey(workOrderEntity.getTemplateId(), corpid);
            if (Objects.isNull(workOrderTemplateEntity)) {
                throw new XbbException(WorkOrderErrorCodeEnum.API_ERROR_222026);
            }
            String scopeRule = workOrderTemplateEntity.getScopeRule();
            JSONObject scopeRuleObj = JSON.parseObject(scopeRule);
            Integer inside = scopeRuleObj.getInteger("inside");
            if (Objects.equals(inside, 1)) {
                UserVO loginUser = workOrderEvaluateDTO.getLoginUser();
                Set<String> permSet = loginUser.getPermSet();
                if (permSet.contains(ProPermissionAliasEnum.WORK_ORDER_RATE.getAlias())) {
                    workOrderEvaluateVO.setEvaluate(1);
                } else {
                    workOrderEvaluateVO.setEvaluate(0);
                }
            } else {
                workOrderEvaluateVO.setEvaluate(0);
            }


        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("WorkOrderEvaluationServiceImpl.getEvaluation出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

        return workOrderEvaluateVO;
    }

    /**
     * Description: 评价工单
     * @param
     * @return
     * @throws
     * @author 刘阳
     * @date 2019/4/15 3:16 PM
     * @since
     */
    @Override
    public WorkOrderEvaluateSaveVO evaluateSave(WorkOrderEvaluateSaveDTO workOrderEvaluateSaveDTO) throws XbbException {
        String corpid = workOrderEvaluateSaveDTO.getCorpid();
        Long workOrderId = workOrderEvaluateSaveDTO.getWorkOrderId();
        Integer rateStar = workOrderEvaluateSaveDTO.getRateStar();
        String rateContent = workOrderEvaluateSaveDTO.getRateContent();

        WorkOrderEntity workOrderEntity = workOrderModel.getByKey(workOrderId, corpid);
        if (Objects.isNull(workOrderEntity) || Objects.equals(workOrderEntity.getDel(), DelEnum.DELETE.getDel())) {
            throw new XbbException(WorkOrderErrorCodeEnum.API_ERROR_222011);
        }
        WorkOrderTemplateEntity workOrderTemplateEntity = workOrderTemplateModel.getBykey(workOrderEntity.getTemplateId(), corpid);
        if (Objects.isNull(workOrderTemplateEntity)) {
            throw new XbbException(WorkOrderErrorCodeEnum.API_ERROR_222026);
        }
        String scopeRule = workOrderTemplateEntity.getScopeRule();
        JSONObject scopeRuleObj = JSON.parseObject(scopeRule);
        Integer inside = scopeRuleObj.getInteger("inside");
        if (Objects.equals(inside, 1)) {
            //TODO 内部评价工单,需处理权限
        }

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("workOrderId", workOrderId);
        param.put("del", DelEnum.NORMAL.getDel());
        Integer entitysCount = workOrderEvaluateModel.getEntitysCount(param);
        if (entitysCount > 0) {
            throw new XbbException(WorkOrderErrorCodeEnum.API_ERROR_222035);
        }
        WorkOrderEvaluateEntity workOrderEvaluateEntity = new WorkOrderEvaluateEntity();
        workOrderEvaluateEntity.setCorpid(corpid);
        workOrderEvaluateEntity.setWorkOrderId(workOrderId);
        workOrderEvaluateEntity.setRateStar(rateStar);
        workOrderEvaluateEntity.setRateContent(rateContent);
        workOrderEvaluateEntity.setEvaluateId(workOrderEvaluateSaveDTO.getUserId());
        workOrderEvaluateEntity.setDel(0);
        workOrderEvaluateModel.insert(workOrderEvaluateEntity);

        //更新工单主表数据
        JSONObject data = workOrderEntity.getData();
        data.put(WorkOrderEnum.RATE_STAR.getAttr(), rateStar);
        workOrderEntity.setData(data);
        workOrderModel.save(workOrderEntity);

        Long id = workOrderEvaluateEntity.getId();
        WorkOrderEvaluateSaveVO workOrderEvaluateSaveVO = new WorkOrderEvaluateSaveVO();
        workOrderEvaluateSaveVO.setId(id);
        // TODO: 2019/5/2 评价推送

        return workOrderEvaluateSaveVO;
    }
}
